package com.example.coroutines_test

import android.os.Bundle
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.coroutines_test.adapter.MyListAdapter
import com.example.coroutines_test.viewmodel.MessageViewModel
import kotlin.random.Random

class MainActivity : AppCompatActivity() {

    /**
     *  这里使用了委派：
     *  访问 每一次访问 messageViewModel 属性
     *  都需要经过 viewModels()方法返回的 ViewModelLazy 对象的 get() 方法
     *  而 get() 方法内部是
     *
     * ViewModelProvider.create(store, factory, extras)
     *                     .get(viewModelClass)
     *
     *  而这与常规的
     *         ViewModelProvider viewModelProvider = new ViewModelProvider(this);
     *         MessageViewModel userViewModel = viewModelProvider.get(MessageViewModel.class);
     *
     * 一模一样
     * 链接：https://juejin.cn/post/6915012483421831175
     *
     */
    private val messageViewModel: MessageViewModel by viewModels()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val tips: TextView = findViewById(R.id.tips)

        val button: Button = findViewById(R.id.query)

        val progression: ProgressBar = findViewById(R.id.progressBar)

        button.setOnClickListener {
            progression.progress = 0
            messageViewModel.fetchUser()
        }

        val recyclerView: RecyclerView = findViewById(R.id.listView)

        recyclerView.layoutManager = LinearLayoutManager(applicationContext,LinearLayoutManager.VERTICAL,true)

        recyclerView.adapter = MyListAdapter( listOf(
            "第1个",
            "第2个",
            "第3个",
            "第4个",
            "第5个",
            "第6个",
            "第7个",
            "第8个",
            "第9个",
            "第10个",
        ))

        val random = Random

        messageViewModel.progress.observe(this){
            progression.progress = it
        }

        messageViewModel.messages.observe(this) {
            it?.let {

                tips.text = it[random.nextInt(10)].title
            }
        }
    }
}